﻿using System.ServiceProcess;
using System.Linq;
using Netfraction.Common.Logging;

namespace NetfractionHub
{
	public partial class NetfractionHubService : ServiceBase
	{
		public static Network.BufferManager SocketBuffer;

		Network.ConnectionListner _connListener;
		Network.ConnectionManager _connManager;
		Security.RoleManager _roleManager;
		Security.IdentityManager _identityManager;

		public NetfractionHubService()
		{
			InitializeComponent();
		}

		protected override void OnStart(string[] args)
		{
			StartApplication();
		}

		public void StartApplication()
		{
			LogManager.WriteEntry("Starting Hub", LogEventId.HubStarted, LogLevel.Basic);

			Settings.HubSettings.LoadSettings();

			SocketBuffer = new Network.BufferManager(16, 1024, 500);//Settings.HubSettings.HubConnection.MaximumUsersCount);

			// DEBUGGING ONLY!!!
			//Settings.HubSettings.HubConnection.ListeningEndPoints[0].Port++;

			if (Settings.HubSettings.HubConnection.ADCS.IsEnabled && !Network.Protocol.ADCS.Security.Certificate.VerifyOrCreateCertificate())
				LogManager.WriteEntry("ADCS Hub Certificate verification or creation failed.", LogEventId.TLSCertificateCreationError, LogLevel.Basic);

			_roleManager = Security.RoleManager.GetInstance();
			Security.RoleManager.LoadRoles();

			_identityManager = Security.IdentityManager.GetInstance();
			Security.IdentityManager.LoadIdentities();
			
			_connManager = Network.ConnectionManager.GetInstance();

			// Define whether a hub owner exists. If no owner exists, the next user to connect will be set as the owner.
			Network.ConnectionManager.HubHasOwner = _identityManager.Identities.Where(p => p.Role != null && p.Role.RoleId == 1).Count() > 0;

			_connListener = Network.ConnectionListner.GetInstance();
			_connListener.Start();
		}

		protected override void OnStop()
		{
			StoppingApplication();
		}

		public void StoppingApplication()
		{
			NetfractionHub.Security.IdentityManager.SaveIdentities();
			NetfractionHub.Settings.HubSettings.SaveSettings();
		}
	}
}
